import React, { useState } from 'react'
import Head from 'next/head'
import Link from 'next/link'
import { Header, Footer, Author, Advert } from '../components/Index'
import { Row, Col, Breadcrumb, Affix } from 'antd'
import { CalendarOutlined, FolderOpenOutlined, FireOutlined } from '@ant-design/icons'
import ReactMarkdown from 'react-markdown'
import MarkNav from 'markdown-navbar';
import 'markdown-navbar/dist/navbar.css';
import style from '../styles/pages/detailed.module.css'
import axios from 'axios'
import { timeConversion } from '../utils/index'
import servicePath from '../config/apiUrl'

const Detailed = (result) => {
  return (
    <div>
      <Head>
        <title>{result.title}</title>
      </Head>
      <Header />
      <Row className='comm_main' justify='center'>
        <Col className='comm_left' xs={24} sm={24} md={16} lg={18} xl={14}>
          <div className='comm_box'>
            <div className='bread_box'>
              <Breadcrumb>
                <Breadcrumb.Item><a href="/">首页</a></Breadcrumb.Item>
                <Breadcrumb.Item><a href={`/list?id=${result.typeName == '视频教程' ? '1' : '2'}`}>{result.typeName}</a></Breadcrumb.Item>
                <Breadcrumb.Item>{result.title}</Breadcrumb.Item>
              </Breadcrumb>
            </div>
            <div>
              <div className={style.detailed_title}>
                {result.title}
              </div>
              <div className={`list_icon ${style.center}`}>
                <CalendarOutlined /><strong>{timeConversion(result.addTime)}</strong>
                <FolderOpenOutlined /><strong>{result.typeName}</strong>
                <FireOutlined /><strong>{result.view_count}人</strong>
              </div>
              <div className={style.detailed_content} >
                <ReactMarkdown
                  children={result.article_content}
                />
              </div>
            </div>
          </div>
        </Col>

        <Col className='comm_right' xs={0} sm={0} md={7} lg={5} xl={4}>
          <Author />
          <Advert />
          <Affix offsetTop={2}>
            <div className={`${style.detailed_nav} comm_box`}>
              <div className={style.nav_title}>文章目录</div>
              <MarkNav
                className={style.article_menu}
                source={result.article_content}
                ordered={false}
              />
            </div>
          </Affix>
        </Col>
      </Row>
      <Footer />
    </div>
  )
}

const getArticleById = (id) => {
  return new Promise((resolve, reject) => {
    axios.get(`${servicePath.getArticleById}${id}`)
      .then(res => {
        resolve(res.data.data[0])
      }).catch(error => {
        console.log('getArticleById:', error)
        reject(error)
      })
  })
}

Detailed.getInitialProps = async (params) => {
  const result = await getArticleById(params.query.id)
  return result
}

export default Detailed
